package article

import (
	"fmt"

	"admin.supervise.limaochuxing.top/admin/schemas/req"
	"admin.supervise.limaochuxing.top/admin/schemas/resp"
	"admin.supervise.limaochuxing.top/core"
	"admin.supervise.limaochuxing.top/core/request"
	"admin.supervise.limaochuxing.top/core/response"
	"admin.supervise.limaochuxing.top/model/article"

	"gorm.io/gorm"
)

type IArticleService interface {
	List(page request.PageReq, listReq req.ArticleListReq) (res response.PageResp, e error)
	Detail(id int) (res resp.ArticleResp, e error)
	Add(addReq req.ArticleAddReq) (e error)
	Edit(editReq req.ArticleEditReq) (e error)
	Del(id int) (e error)
	Change(id int) (e error)
}

//NewArticleService 初始化
func NewArticleService(db *gorm.DB) IArticleService {
	return &articleService{db: db}
}

//articleService 文章资讯服务实现类
type articleService struct {
	db *gorm.DB
}

//List 文章资讯列表
func (srv articleService) List(page request.PageReq, listReq req.ArticleListReq) (res response.PageResp, e error) {

	// 分页信息
	limit := page.PageSize
	offset := page.PageSize * (page.PageNo - 1)
	articleTbName := core.DBTableName(&article.Article{})
	articleCategoryTbName := core.DBTableName(&article.ArticleCategory{})
	// 查询
	// model := srv.db.Model(&article.Article{})
	// 修改查询语句
	model := srv.db.Table(articleTbName+" as article").
		Joins(fmt.Sprintf("LEFT JOIN %s ON article.cid = %s.id",articleCategoryTbName,articleCategoryTbName)).
		Select(fmt.Sprintf("article.*, %s.name as category",articleCategoryTbName))

    if listReq.Cid >0 {
        model = model.Where("cid = ?", listReq.Cid)
    }
	if listReq.Title != "" {
        model = model.Where("title like ?", "%"+listReq.Title+"%")
    }
    if listReq.Intro != "" {
        model = model.Where("intro = ?", listReq.Intro)
    }
    if listReq.Summary != "" {
        model = model.Where("summary = ?", listReq.Summary)
    }
    if listReq.Image != "" {
        model = model.Where("image = ?", listReq.Image)
    }
    if listReq.Content != "" {
        model = model.Where("content = ?", listReq.Content)
    }
    if listReq.Author != "" {
        model = model.Where("author = ?", listReq.Author)
    }
    if listReq.Visit >0 {
        model = model.Where("visit = ?", listReq.Visit)
    }
    if listReq.Sort >0 {
        model = model.Where("article.sort = ?", listReq.Sort)
    }
    if listReq.IsShow >0 {
        model = model.Where("article.is_show = ?", listReq.IsShow)
    }
	model = model.Where("article.is_delete = ?", 0)
	// 总数
	var count int64
	err := model.Count(&count).Error
	if e = response.CheckErr(err, "List Count err"); e != nil {
		return
	}
	// 数据
	// 修改扫描字段
	type Result struct {
		article.Article
		Category string `gorm:"column:category"`
	}
	var objs []Result
	err = model.Limit(limit).Offset(offset).Order("id desc").Find(&objs).Error
	if e = response.CheckErr(err, "List Find err"); e != nil {
		return
	}
	resps := []resp.ArticleResp{}
	response.Copy(&resps, objs)
	// 手动复制分类名称字段
	for i := range resps {
		resps[i].Category = objs[i].Category
	}
	return response.PageResp{
		PageNo:   page.PageNo,
		PageSize: page.PageSize,
		Count:    count,
		Lists:    resps,
	}, nil
}

//Detail 文章资讯详情
func (srv articleService) Detail(id int) (res resp.ArticleResp, e error) {
	var obj article.Article
	err := srv.db.Where("id = ? AND is_delete = ?", id, 0).Limit(1).First(&obj).Error
	if e = response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		return
	}
	if e = response.CheckErr(err, "Detail First err"); e != nil {
		return
	}
	response.Copy(&res, obj)
    // res.Avatar = util.UrlUtil.ToAbsoluteUrl(res.Avatar)
	return
}

//Add 文章资讯新增
func (srv articleService) Add(addReq req.ArticleAddReq) (e error) {
	var obj article.Article
	response.Copy(&obj, addReq)
	err := srv.db.Create(&obj).Error
	e = response.CheckErr(err, "Add Create err")
	return
}

//Edit 文章资讯编辑
func (srv articleService) Edit(editReq req.ArticleEditReq) (e error) {
	var obj article.Article
	err := srv.db.Where("id = ? AND is_delete = ?", editReq.Id, 0).Limit(1).First(&obj).Error
	// 校验
	if e = response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		return
	}
	if e = response.CheckErr(err, "Edit First err"); e != nil {
		return
	}
	// 更新
	response.Copy(&obj, editReq)
	err = srv.db.Model(&obj).Updates(obj).Error
	e = response.CheckErr(err, "Edit Updates err")
	return
}

//Del 文章资讯删除
func (srv articleService) Del(id int) (e error) {
	var obj article.Article
	err := srv.db.Where("id = ? AND is_delete = ?", id, 0).Limit(1).First(&obj).Error
	// 校验
	if e = response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		return
	}
	if e = response.CheckErr(err, "Del First err"); e != nil {
		return
	}
    // 删除
    obj.IsDelete = 1
    err = srv.db.Save(&obj).Error
    e = response.CheckErr(err, "Del Save err")
	return
}

//Change 切换文章显示状态
func (srv articleService) Change(id int) (e error) {
	var obj article.Article
	err := srv.db.Where("id = ? AND is_delete = ?", id, 0).Limit(1).First(&obj).Error
	// 校验
	if e = response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		return
	}
	if e = response.CheckErr(err, "Change First err"); e != nil {
		return
	}
	
	// 更新状态：如果当前是1则变为0，如果是0则变为1
	newStatus := 1 - obj.IsShow
	err = srv.db.Model(&obj).Update("is_show", newStatus).Error
	e = response.CheckErr(err, "Change Update err")
	return
}